<template>
    <view class="package">
        <view class="desc">
            <div class="chat-container">
                <!-- 标题栏 -->
                <div class="header-bar">
                    <button class="back-btn" @click="handleBack">
                        <img src="@/static/svg/返回.svg" alt="返回" class="icon" />
                    </button>
                    <h2 class="title">{{ nickname }}</h2>
                    <button class="more-btn">
                        <img src="@/static/svg/更多.svg" alt="返回" class="icon" />
                    </button>
                </div>

                <!-- 消息列表容器 -->
                <div class="message-container">
                    <div v-for="(message, index) in messages" :key="index" class="message">
                        <img v-if="!message.self" :src="message.avatar" alt="Avatar" class="avatar">
                        <div v-if="!message.self" class="message-content">
                            <p>{{ message.text }}</p>
                        </div>
                        <div v-if="message.self" class="message-content self-message">
                            <p>{{ message.text }}</p>
                        </div>
                        <img v-if="message.self" :src="message.avatar" alt="Avatar" class="avatar self-avatar">
                    </div>
                </div>

                <!-- 输入区域 -->
                <view class="input-area" @click="handleRefresh">
                    <button class="voice-btn">
                        <img src="@/static/svg/微信语音.svg" alt="语音" class="icon" />
                    </button>
                    <textarea readonly style="pointer-events: none" @keydown.prevent></textarea>
                    <button class="emoji-btn">
                        <img src="@/static/svg/微信表情.svg" alt="语音" class="icon" />
                    </button>
                    <button class="more-btn">
                        <img src="@/static/svg/预览微信-更多.svg" alt="语音" class="icon" />
                    </button>
                </view>
            </div>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import OpenAI from 'openai';

const nickname = ref('');

const handleBack = async () => {
    // 返回上一页
    uni.navigateTo({
        url: `/pages/index/index`
    });
};

interface Message {
    text: string | null;
    avatar: string;
    self: boolean;
}

const messages = ref<Message[]>([
    { text: '正在努力思考中，请稍后。。。', avatar: uni.getStorageSync('taAvatar') || '/static/img/taImg.jpg', self: false },
    { text: '欢迎游玩小丑模拟器', avatar: uni.getStorageSync('taAvatar') || '/static/img/taImg.jpg', self: false },
    { text: '小丑模拟器仅供学习和娱乐', avatar: uni.getStorageSync('taAvatar') || '/static/img/taImg.jpg', self: false },
    { text: '小丑模拟器无任何盈利方式', avatar: uni.getStorageSync('taAvatar') || '/static/img/taImg.jpg', self: false },
    { text: '小丑模拟器99%的代码由AI生成', avatar: uni.getStorageSync('yourAvatar') || '/static/img/ijpg.jpg', self: true },
    { text: '小丑模拟器由群主一次麦联合出品', avatar: uni.getStorageSync('taAvatar') || '/static/img/taImg.jpg', self: false },
    { text: '答应我，不要做小丑！', avatar: uni.getStorageSync('yourAvatar') || '/static/img/ijpg.jpg', self: true },
    { text: '正在玩命的生成中，请稍后。。。', avatar: uni.getStorageSync('taAvatar') || '/static/img/taImg.jpg', self: false }
]);

const userContent = ref('');

const openai = new OpenAI({
    baseURL: 'https://api.deepseek.com',
    apiKey: import.meta.env.VITE_DEEPSEEK_API_KEY,
    dangerouslyAllowBrowser: true
});

const isLoading = ref(false);

const refreshTxt = async () => {
    try {
        const res = await uni.request({
            url: '/static/txt/tishici.txt',
            method: 'GET',
            responseType: 'text'
        });

        if (res.statusCode === 200) {
            // 使用正则匹配非空行作为有效提示词
            const prompts = (res.data as string).match(/^.*\S+.*$/gm) || [];
            const tempString = prompts.join('\n');

            // 修改正则表达式使用捕获组提取括号内容
            const bracketContents = Array.from(tempString.matchAll(/\((.*?)\)/gs))
                .map(m => m[1])
                .filter(Boolean);

            // bracketContents.forEach(
            //     (item, index) => console.log(`第${index}项：${item}`)
            // );

            // 从bracketContents里面随机获取一个值丢给userContent
            const randomIndex = Math.floor(Math.random() * bracketContents.length);
            userContent.value = bracketContents[randomIndex] || '';
            // console.log('提示词加载:', userContent.value);
        } else {
            throw new Error('文件请求失败：' + res.errMsg);
        }
    } catch (error) {
        console.error('提示词加载失败:', error);
        uni.showToast({
            title: '提示词加载失败',
            icon: 'none',
            duration: 2000
        });
        userContent.value = '默认提示词';
    }
}

const handleRefresh = async () => {

    if (!import.meta.env.VITE_DEEPSEEK_API_KEY) {
        uni.showToast({
            title: '请先配置deepseek的API Key，在.env文件配置',
            icon: 'none',
            duration: 5000
        });
        return;
    }

    isLoading.value = true;

    await refreshTxt();   

    uni.showLoading({ title: '正在玩命生成中...', mask: true });
    try {
        console.log('开始请求API');
        const completion = await openai.chat.completions.create({
            messages: [
                { role: 'system', content: `你是一个专业生成舔狗聊天记录的大师，你生成的聊天记录最后总是会出乎意料的反转，你生成的聊天记录中女方的回复不是冷漠的就是敷衍的甚至是粗暴的，偶尔会辱骂男方下头，你生成的聊天记录最多不超过150字，你生成的聊天记录会以标准的JSON格式包装好。在这个JSON对象中，messages是一个数组，包含了数个对象，每个对象代表一条消息，包含text（文本内容）、avatar（头像链接）和self（是否为自己发送的标志）三个字段` },
                { role: 'user', content: `我会给你一段参考案例，这些聊天记录里false代表女方，true代表男方，这些聊天记录通常会凸显男方的舔狗行为非常的小丑，你需要深刻理解这段聊天记录的笑点，然后生成一段全新的但是类似笑点的聊天记录，这是可以参考的案例：` + userContent.value }
            ],
            model: 'deepseek-chat',
        });

        try {
            const content = completion.choices[0].message.content ?? '';
            // 改为贪婪匹配模式
            const jsonString = content.match(/\{[\s\S]*\}/s)?.[0];
            if (!jsonString) throw new Error('未找到有效JSON数据');

            // console.log('原始JSON字符串:', jsonString);

            const response = JSON.parse(jsonString);
            if (response?.messages?.length && Array.isArray(response.messages)) {
                messages.value = response.messages.filter((m: Message) => {
                    return typeof m.text === 'string' &&
                        typeof m.avatar === 'string' &&
                        typeof m.self === 'boolean';
                }).map((message: Message) => {
                    if (!message.self) {
                        return { ...message, avatar: uni.getStorageSync('taAvatar') || '/static/img/taImg.jpg' };
                    } else {
                        return { ...message, avatar: uni.getStorageSync('yourAvatar') || '/static/img/ijpg.jpg' };
                    }
                });
                console.log('当前消息数量:', messages.value.length);
            } else {
                console.error('无效的消息格式:', response);
                throw new Error('API返回消息格式不正确');
            }
        } catch (error) {
            console.error('完整错误信息:', error);
            messages.value.push({
                text: `解析失败: ${error instanceof Error ? error.message : '未知错误'}`,
                avatar: 'https://mms1.baidu.com/it/u=598647648,2707802622&fm=253&app=120&f=JPEGw=500&h=500',
                self: false
            });
            throw error;
        }
    } catch (error) {
        console.error('API请求失败:', error);
    } finally {
        isLoading.value = false;
        uni.hideLoading();
    }
};

onMounted(() => {
    nickname.value = uni.getStorageSync('taName');

    handleRefresh();
});
</script>

<style scoped lang="scss">
.package {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center
}

.desc {
    height: 100%;
    width: 100%;
    max-width: 520px;
}

.chat-container {
    height: 100%;
    width: 100%;
    min-width: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    background-color: #f5f5f5;
    box-sizing: border-box;
}

.message-container {
    flex: 1;
    overflow: hidden;
    padding: 12px 16px;
}

.header-bar {
    background: #f5f5f5;
    height: 48px;
    display: flex;
    align-items: center;
    padding: 0 16px;
    border-bottom: 1px solid #e0e0e0;

    .back-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 100%;
        color: #666666;
        background: none;
        border: none;
        border-radius: 0;
        transition: color 0.2s ease;
    }

    .back-btn img {
        width: 24px;
    }

    .title {
        flex: 1;
        font-family: Arial, sans-serif;
        font-size: 16px;
        color: #000000;
        line-height: 24px;
        margin: 8px 0;
        text-align: center;
    }

    .more-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 100%;
        color: #666666;
        background: none;
        border: none;
        border-radius: 0;
        transition: color 0.2s ease;
    }

    .more-btn img {
        width: 24px;
    }
}

.message-container {
    flex: 1;
    overflow-y: auto;
    padding: 12px 16px;
    scrollbar-width: none;

    /* Firefox */
    &::-webkit-scrollbar {
        display: none;
        /* Chrome/Safari */
    }
}

.input-area {
    height: 80px;
    border-top: 1px solid #e0e0e0;
    padding: 0px 9px 16px 9px;
    display: flex;
    gap: 8px;
    align-items: center;

    textarea {
        flex: 1;
        height: 30px;
        padding: 6px 8px;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        font-family: system-ui, sans-serif;
        font-size: 16px;
        color: #000000;
        background: #ffffff;
        resize: none;

        &::placeholder {
            color: #bdbdbd;
        }
    }

    .voice-btn,
    .emoji-btn,
    .more-btn {
        width: 40px;
        height: 30px;
        background: transparent;
        border: none;
        padding: 8px;
        display: flex;
        align-items: center;
        justify-content: center;

        img {
            /* 需要后续添加图标 */
            width: 30px;
            height: 30px;
            fill: #666666;
        }
    }
}


button[disabled] {
    opacity: 0.5;
    cursor: not-allowed !important;
}

button[disabled]:hover {
    background: transparent !important;
}


.chat-messages {
    padding: 10px;
}

.message {
    display: flex;
    color: #000000;
    margin-bottom: 10px;

}

.message.self {
    justify-content: flex-end;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
}

.avatar.self-avatar {
    margin-left: 10px;
    margin-right: 0;
}

.message-content {
    max-width: 70%;
    padding: 15px 15px;
    background-color: white;
    border-radius: 8px;
    display: flex;
    align-items: center;
    text-align: left;
    letter-spacing: 1.1px;
    margin-bottom: 10px
}

.message-content.self-message {
    background-color: #3adf06;
    margin-left: auto;
}
</style>

const router = useRouter();

const handleBack = () => {
router.push('/');
};